//
//  NewerRegisterViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/16.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "NewerRegisterViewController.h"
#import "SetLoginCodeViewController.h"

static int i = 59;
@interface NewerRegisterViewController ()<UINavigationControllerDelegate, UITextFieldDelegate>
@property (nonatomic, strong)UIImageView * iconImgView;
@property (nonatomic, strong)UITextField * phoneTextField;
@property (nonatomic, strong)UITextField * codeTextField;
@property (nonatomic, strong)UITextField * inviteTextField;
@property (nonatomic, strong)UIButton * getVerificationCodeBtn;//获取验证码
@property (nonatomic, strong)NSString * telNumStr;//电话号码
@property (nonatomic, strong)NSTimer *timmer;
@property (nonatomic, strong)NSString * inviteCodeStr;//邀请码
@end

@implementation NewerRegisterViewController(networking)
//注册
- (void)registerAccount{
    NSString * timeStr = [self currentTimeStr];
    //邀请码
    self.inviteCodeStr = self.inviteTextField.text;
    if (self.inviteTextField.text == nil) {
        self.inviteCodeStr = @"";
    }
    //str
    NSDictionary * dic = @{@"phone":self.phoneTextField.text,
                           @"t":timeStr,
                           @"phone_code":self.codeTextField.text,
                           @"invite_code":self.inviteCodeStr
                           };
    //sign
    NSDictionary * signDic = @{@"phone":self.phoneTextField.text,
                               @"t":timeStr,
                               @"phone_code":self.codeTextField.text,
                               @"invite_code":self.inviteCodeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/register/index?api=api1001"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError.code == -1001) {
            [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([compareMD5Str isEqualToString:signResult]) {
                //            self.bidTypeArr = jsonData[@"body"];
                //            [self.tableView reloadData];
                [self.view makeToast:@"注册成功" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                    SetLoginCodeViewController * vc = [[SetLoginCodeViewController alloc] init];
                    vc.inviteCodeStr = self.inviteCodeStr;
                    [self.navigationController pushViewController:vc animated:YES];
                    NSLog(@"成功");
                }];
            }else{
                NSLog(@"失败");
            }
        }
    }];
}
//发送验证码
- (void)sendMessageCode{
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{@"phone":self.phoneTextField.text,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{@"phone":self.phoneTextField.text,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/sendCode/index?api=api1001"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            //        NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            //        NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            //        NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            //        if ([compareMD5Str isEqualToString:signResult]) {
            //            NSLog(@"成功");
            //        }else{
            //            NSLog(@"失败");
            //        }
        }
    }];
}
@end

@implementation NewerRegisterViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpViews];
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
}
- (void)setUpViews{
    //图标
    self.iconImgView = [[UIImageView alloc] init];
    //左上角×
    UIImageView * closeImg = [[UIImageView alloc] init];
    int iconW = 150/WIDTH_6_SCALE;
    if (Is_Iphone_X) {
        self.iconImgView.frame = CGRectMake((SCREEN_WIDTH - iconW)/2, 60/WIDTH_6_SCALE + 24, iconW, 43.5/WIDTH_6_SCALE);
        closeImg.frame = CGRectMake(18/WIDTH_6_SCALE, 34/WIDTH_6_SCALE + 24, 15/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    }else{
        self.iconImgView.frame = CGRectMake((SCREEN_WIDTH - iconW)/2, 60/WIDTH_6_SCALE, iconW, 43.5/WIDTH_6_SCALE);
        closeImg.frame = CGRectMake(18/WIDTH_6_SCALE, 34/WIDTH_6_SCALE, 15/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    }
    self.iconImgView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.iconImgView];
    closeImg.backgroundColor = [UIColor blackColor];
    [self.view addSubview:closeImg];
    UIButton * coverCloseBtn = [[UIButton alloc] initWithFrame:CGRectMake(closeImg.left - 14/WIDTH_6_SCALE, closeImg.top - 14/WIDTH_6_SCALE, closeImg.width + 28/WIDTH_6_SCALE, closeImg.width + 28/WIDTH_6_SCALE)];
    [coverCloseBtn setBackgroundColor:[UIColor orangeColor]];
    [self.view addSubview:coverCloseBtn];
    [coverCloseBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //注册账号
    UILabel * registerAccountLab = [[UILabel alloc] initWithFrame:CGRectMake(0, self.iconImgView.bottom + 70/WIDTH_6_SCALE, SCREEN_WIDTH, 15/WIDTH_6_SCALE)];
    [self label:registerAccountLab withFont:DEF_FontSize_18 withText:@"注册账号" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentCenter withView:self.view];
    //手机图案
    int phoneImgX = 50/WIDTH_6_SCALE;
    UIImageView * phoneImg = [[UIImageView alloc] initWithFrame:CGRectMake(phoneImgX, registerAccountLab.bottom + 32/WIDTH_6_SCALE, 12/WIDTH_6_SCALE, 20/WIDTH_6_SCALE)];
    phoneImg.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:phoneImg];
    //上面的输入框
    self.phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(phoneImg.right + 12/WIDTH_6_SCALE, 0, SCREEN_WIDTH - phoneImg.right - 12/WIDTH_6_SCALE - phoneImg.left, 22/WIDTH_6_SCALE)];
    self.phoneTextField.delegate = self;
    self.phoneTextField.centerY = phoneImg.centerY;
    self.phoneTextField.font = DEF_FontSize_12;
    self.phoneTextField.placeholder = @"请输入手机号码";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.phoneTextField];
    //上面横线
    UIView * topLineView = [[UIView alloc] initWithFrame:CGRectMake(phoneImg.left, phoneImg.bottom + 8/WIDTH_6_SCALE, SCREEN_WIDTH - phoneImgX*2, 1/WIDTH_6_SCALE)];
    topLineView.backgroundColor = getColor(grayColor);
    [self.view addSubview:topLineView];
    //锁头图案
    UIImageView * lockImg = [[UIImageView alloc] initWithFrame:CGRectMake(phoneImg.left, topLineView.bottom + 32/WIDTH_6_SCALE, 16/WIDTH_6_SCALE, phoneImg.height)];
    lockImg.centerX = phoneImg.centerX;
    lockImg.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:lockImg];
    //下面输入框
    self.codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneTextField.left, 0, self.phoneTextField.width, self.phoneTextField.height)];
    self.codeTextField.centerY = lockImg.centerY;
    self.codeTextField.delegate = self;
    self.codeTextField.font = DEF_FontSize_12;
    self.codeTextField.placeholder = @"请输入验证码";
    [self.view addSubview:self.codeTextField];
    //获取验证码按钮
    int getVerificationCodeBtnW = 90/WIDTH_6_SCALE;
    self.getVerificationCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneTextField.right - getVerificationCodeBtnW, 0, getVerificationCodeBtnW, 30/WIDTH_6_SCALE)];
    self.getVerificationCodeBtn.centerY = self.codeTextField.centerY;
    [self.getVerificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.getVerificationCodeBtn addTarget:self action:@selector(getVerificationCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.getVerificationCodeBtn setBackgroundColor:[UIColor orangeColor]];
    [self button:self.getVerificationCodeBtn withBGColor:[UIColor orangeColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    [self.getVerificationCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.getVerificationCodeBtn.titleLabel.font = DEF_FontSize_12;
    [self.view addSubview:self.getVerificationCodeBtn];
    //下面横线
    UIView * bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(topLineView.left, lockImg.bottom + 8/WIDTH_6_SCALE, topLineView.width, topLineView.height)];
    bottomLineView.backgroundColor = getColor(grayColor);
    [self.view addSubview:bottomLineView];
    //礼物图案
    UIImageView * giftImg = [[UIImageView alloc] initWithFrame:CGRectMake(phoneImg.left, bottomLineView.bottom + 32/WIDTH_6_SCALE, 16/WIDTH_6_SCALE, phoneImg.height)];
    giftImg.centerX = phoneImg.centerX;
    giftImg.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:giftImg];
    //最下面输入框
    self.inviteTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneTextField.left, 0, self.phoneTextField.width, self.phoneTextField.height)];
    self.inviteTextField.centerY = giftImg.centerY;
    self.inviteTextField.delegate = self;
    self.inviteTextField.font = DEF_FontSize_12;
    self.inviteTextField.placeholder = @"请输入邀请码(可不填)";
    [self.view addSubview:self.inviteTextField];
    //最下面横线
    UIView * downLineView = [[UIView alloc] initWithFrame:CGRectMake(topLineView.left, giftImg.bottom + 8/WIDTH_6_SCALE, topLineView.width, topLineView.height)];
    downLineView.backgroundColor = getColor(grayColor);
    [self.view addSubview:downLineView];
    //登录
    int loginBtnX = 48/WIDTH_6_SCALE;
    UIButton * registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(loginBtnX, downLineView.bottom + 36/WIDTH_6_SCALE, SCREEN_WIDTH - loginBtnX*2, 37/WIDTH_6_SCALE)];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registerBtn.titleLabel.font = DEF_FontSize_14;
    [registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self button:registerBtn withBGColor:getColor(@"3675bd") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    //已有账号去登录
    UIButton * haveAccountBtn = [[UIButton alloc] initWithFrame:CGRectMake(loginBtnX, registerBtn.bottom + 36/WIDTH_6_SCALE, SCREEN_WIDTH - loginBtnX*2, 37/WIDTH_6_SCALE)];
    [haveAccountBtn setTitle:@"已有账号，去登陆" forState:UIControlStateNormal];
    [haveAccountBtn setTitleColor:getColor(@"3675bd") forState:UIControlStateNormal];
    haveAccountBtn.titleLabel.font = DEF_FontSize_12;
    [haveAccountBtn addTarget:self action:@selector(haveAccountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self button:haveAccountBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:YES withViwe:self.view];
    //隐私规则和服务条款
    UILabel * frontLab = [[UILabel alloc] init];
    [self label:frontLab withFont:DEF_FontSize_10 withText:@"注册福乐猪即为阅读和默认" withTextColor:getColor(@"cbcbcb") withTextAlignment:NSTextAlignmentRight withView:self.view];
    //隐私规则
    UIButton * privacyBtn = [[UIButton alloc] init];
    [self button:privacyBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:self.view];
    privacyBtn.titleLabel.font = DEF_FontSize_10;
    NSMutableAttributedString *privacyTitle = [[NSMutableAttributedString alloc] initWithString:@"隐私规则"];
    NSRange privacyTitleRange = {0,[privacyTitle length]};
    [privacyTitle addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:privacyTitleRange];
    [privacyTitle addAttribute:NSForegroundColorAttributeName value:getColor(@"cbcbcb") range:privacyTitleRange];
    [privacyBtn setAttributedTitle:privacyTitle
                          forState:UIControlStateNormal];
    [privacyBtn addTarget:self action:@selector(privacyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:privacyBtn];
    //和
    UILabel * andLab = [[UILabel alloc] init];
    [self label:andLab withFont:DEF_FontSize_10 withText:@"和" withTextColor:getColor(@"cbcbcb") withTextAlignment:NSTextAlignmentCenter withView:self.view];
    //服务条款
    UIButton * serveBtn = [[UIButton alloc] init];
    [self button:serveBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:self.view];
    serveBtn.titleLabel.font = DEF_FontSize_10;
    [serveBtn addTarget:self action:@selector(serveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    NSMutableAttributedString *serveTitle = [[NSMutableAttributedString alloc] initWithString:@"服务条款"];
    NSRange serveTitleRange = {0,[serveTitle length]};
    [serveTitle addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:serveTitleRange];
    [serveTitle addAttribute:NSForegroundColorAttributeName value:getColor(@"cbcbcb") range:serveTitleRange];
    [serveBtn setAttributedTitle:serveTitle
                          forState:UIControlStateNormal];
    [self.view addSubview:serveBtn];
    __weak typeof (self)weakSelf = self;
    [frontLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).mas_offset(72/WIDTH_6_SCALE);
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(- BOTTOM_HEIGHT - 34/WIDTH_6_SCALE);
        make.height.mas_offset(12/WIDTH_6_SCALE);
    }];
    [privacyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(frontLab.mas_right).mas_offset(2/WIDTH_6_SCALE);
        make.top.height.equalTo(frontLab);
    }];
    [andLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(privacyBtn.mas_right).mas_offset(2/WIDTH_6_SCALE);
        make.top.height.equalTo(frontLab);
    }];
    [serveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(andLab.mas_right).mas_offset(2/WIDTH_6_SCALE);
        make.top.height.equalTo(frontLab);
    }];
}
#pragma mark - action
- (void)closeBtnClick:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)wechatBtnClick:(UIButton *)sender{
    NSLog(@"用微信登录");
}
- (void)getVerificationCodeBtnClick:(UIButton *)sender{
    NSLog(@"获取验证码");
//    self.phoneTextField.text = @"15804299204";
    if ([self valiMobile:self.phoneTextField.text]) {
        self.telNumStr = self.phoneTextField.text;
        //获取验证码
        [self sendMessageCode];
        //初始化定时器
        _timmer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test:) userInfo:nil repeats:YES];
    }else{
        [self.view makeToast:@"请正确填写手机号码" duration:1 position:CSToastPositionCenter style:nil];
        return;
    }
}
- (void)test:(NSTimer *)timmer{
    NSString *str = [NSString stringWithFormat:@"%d后重试",i];
    self.getVerificationCodeBtn.titleLabel.text = str;
    self.getVerificationCodeBtn.userInteractionEnabled = NO;
    i--;
    if (i == -1) {
        [timmer invalidate];
        self.getVerificationCodeBtn.titleLabel.text = @"获取验证码";
        self.getVerificationCodeBtn.userInteractionEnabled = YES;
        i = 59;
    }
}
- (void)registerBtnClick:(UIButton *)sender{
    NSLog(@"注册");
    if (self.phoneTextField.text.length < 11) {
        [self.view makeToast:@"请正确填写手机号码" duration:1 position:CSToastPositionCenter style:nil];
        return;
    }
    if ([self valiMobile:self.phoneTextField.text]) {
        NSLog(@"成功");
//        SetLoginCodeViewController * vc = [[SetLoginCodeViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
        [self registerAccount];
    }else{
        [self.view makeToast:@"请正确填写手机号码" duration:1 position:CSToastPositionCenter style:nil];
        return;
    }
}
- (void)haveAccountBtnClick:(UIButton *)sender{
    NSLog(@"已有账号，去登陆");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)serveBtnClick:(UIButton *)sender{
    NSLog(@"服务条款");
}
- (void)privacyBtnClick:(UIButton *)sender{
    NSLog(@"隐私规则");
}
- (void)textFieldDidChange :(UITextField *)theTextField{
    if (self.phoneTextField) {
        if (self.phoneTextField.text.length == 11) {
            if ([self valiMobile:self.phoneTextField.text]) {
                NSLog(@"%@", self.phoneTextField.text);
            }else{
                [self.view makeToast:@"请正确填写手机号码" duration:1 position:CSToastPositionTop style:nil];
                return;
            }
        }
        if (self.phoneTextField.text.length > 11) {
            [self.view makeToast:@"请正确填写手机号码" duration:1 position:CSToastPositionTop style:nil];
            return;
        }
    }
}
@end
